package com.xw.wuliu;


import java.io.StringReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import com.corey.handler.MyContentHandler;
import com.corey.utils.FileUtils;
import com.corey.utils.HttpDownloader;

import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
	private static final String PREFS_USERINFO = "MyUserInfo";

	private Button btLogin = null;
	private Button btExit = null;
	private EditText edt_user = null;
	private EditText edt_pwd = null;
	private CheckBox rememberPwd = null;
	
	private String m_userNam= null;
	private String m_strPwd = null;
	public static String m_devId = null;
	MyHandler myHandler;
	
	class MyHandler extends Handler{
		public MyHandler(){
			
		}
		public MyHandler(Looper looper){
			super(looper);
		}
		@Override
		public void handleMessage(Message msg) {
			Bundle b = msg.getData();
			int flag = b.getInt("flag");
			if (flag == 1) {
				String userName = b.getString("userName");
				String password = b.getString("password");
//				System.out.println("userName:" + userName + ",password:"
//						+ password);
//				System.out.println("Handler--->"
//						+ Thread.currentThread().getId());
//				System.out.println("handlerMessage");

				boolean bl = isCheckUserPwd(userName,password);
				if(true == bl){
					//登录成功后进入地图页
//                  Intent mapIntent = new Intent();
//                  mapIntent.setClass(MainActivity.this, MapSignInActivity.class);
//                  MainActivity.this.startActivity(mapIntent);
					
					 Intent funcIntent = new Intent();
					 funcIntent.putExtra("username", userName);
		             funcIntent.setClass(MainActivity.this, FuncEnterActivity.class);
		             MainActivity.this.startActivity(funcIntent);
				}else{
					Toast.makeText(getApplicationContext(), "登陆失败", 1).show();
				}
			}else{
				
			}
		}
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		setupView();
	}

	/*
	 * 获得手机IMEI号
	 * 
	 */
	
	public String getIMEI()
	{
		TelephonyManager telephonyManager =(TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
		
		return telephonyManager.getDeviceId();
	}
	
	

	public void setupView() {

		//System.out.println("main--->" + Thread.currentThread().getId());

		myHandler = new MyHandler();
		
		findViews();
		
		String devId = getIMEI();

		//IME号
//		edt_user.setText(devId);
		m_devId = devId;
		
		setListensers();
		//载入用户信息
		loadUserDate();
		
		return;
	}
	
	private void findViews() {
		edt_user = (EditText) findViewById(R.id.edt_user);
		edt_pwd = (EditText) findViewById(R.id.edt_pwd);
		btLogin = (Button) findViewById(R.id.btLogin);
		rememberPwd = (CheckBox) findViewById(R.id.checkBox_jizhumima);
		btExit = (Button) findViewById(R.id.btExit);
	}
	
	private void setListensers(){
		
		btLogin.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				
				boolean  isCorrect = checkUserPwd();
				
//				if(isCorrect == false)
//				{
//					Toast.makeText(MainActivity.this, "用户名和密码都为必填项", Toast.LENGTH_LONG).show();
//					return;
//				}
				
				Log.i("wuliu","will login");
				
				 //add code here
				//登录WEB服务器进行中...
				
				HandlerThread handlerThread = new HandlerThread("handler_thread");
				handlerThread.start();
				MyHandler myHandler = new MyHandler(handlerThread.getLooper());
				Message msg = myHandler.obtainMessage();
				Bundle b = new Bundle();
				b.putInt("flag", 1);
//				System.out.println(edt_user.getText().toString());
				b.putString("userName", edt_user.getText().toString());
				b.putString("password", edt_pwd.getText().toString());
				msg.setData(b);
				msg.sendToTarget();
				
				//保存用户信息
				saveUserDate();
				
				
				//登录成功后进入地图页
//                    Intent mapIntent = new Intent();
//                    mapIntent.setClass(MainActivity.this, MapSignInActivity.class);
//                    MainActivity.this.startActivity(mapIntent);
				
              //Intent funcIntent = new Intent();
              //funcIntent.setClass(MainActivity.this, FuncEnterActivity.class);
              //MainActivity.this.startActivity(funcIntent);
                    
			}

		});
		btExit.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				MainActivity.this.finish();
			}
		});
	}
	
	
	//从服务器验证用户名、密码
	static public boolean isCheckUserPwd(String user,String pass){
//		new LoginTask("sa","1234",this).execute(null);
		String strflag="";
		List<String> strs = new ArrayList<String>();
		HttpDownloader hd = new HttpDownloader();
		String resultStr = hd.download(FileUtils.urlStr+"login?userPsname="+user+"&password="+pass);
		System.out.println("result:"+resultStr);
		
		try{
			//����һ��SAXParserFactory
			SAXParserFactory factory = SAXParserFactory.newInstance();
			XMLReader reader = factory.newSAXParser().getXMLReader();
			//ΪXMLReader�������ݴ�����
			MyContentHandler myContentHandler = new MyContentHandler(strs);
			reader.setContentHandler(myContentHandler);
			//��ʼ�����ļ�
			reader.parse(new InputSource(new StringReader(resultStr)));
			for (Iterator iterator = strs.iterator(); iterator.hasNext();) {
				strflag = (String) iterator.next();
//				System.out.println("Str@@@@"+ string);
			}
		}
		catch(Exception e){
			e.printStackTrace();
		}
			
		if("login_success".equals(strflag)){
			return true;
		}else{
			return false;
		}
	}
	
	//验证用户名、密码的填写是否为空
	public boolean  checkUserPwd()
	{
		m_userNam = edt_user.getText().toString();
		 m_strPwd = edt_pwd.getText().toString();
		
		if(m_userNam.equals("") || m_strPwd.equals(""))
		{
			    return false;
		}
		return true;
	}
	
	public void resultHandle(boolean isSuccess){
		
	}
	
	/**
	 * 保存用户信息
	 */
	private void saveUserDate(){
		//载入配置文件
		SharedPreferences sp = getSharedPreferences(PREFS_USERINFO, 0);
		//写入配置文件
		Editor spEd = sp.edit();
		if (rememberPwd.isChecked()) {
			spEd.putBoolean("isSave", true);
			spEd.putString("name", edt_user.getText().toString());
			spEd.putString("password", edt_pwd.getText().toString());
		} else {
			spEd.putBoolean("isSave", false);
			spEd.putString("name", "");
			spEd.putString("password", "");
		}
		spEd.commit();
	}
	
	/**
	 * 载入用户信息
	 */
	private void loadUserDate() {
		SharedPreferences sp = getSharedPreferences(PREFS_USERINFO, 0);

		if (sp.getBoolean("isSave", false)) {
			String username = sp.getString("name", "");
			String userpassword = sp.getString("password", "");
			if (!("".equals(username) && "".equals(userpassword))) {
				edt_user.setText(username);
				edt_pwd.setText(userpassword);
				rememberPwd.setChecked(true);
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
